<template>
  <div class="policy-manage-bg">
    <el-card class="map-bg" v-show="isShowMap">
      <div id="policyMap"></div>
      <div class="search-bg-a" v-if="isShowIcon">
        <i class="el-icon-search" @click="showIconFn(false)"></i>
      </div>
      <div class="search-bg-b" v-else>
        <el-form ref="queryForm" v-model="queryForm" label-width="90px">
          <el-form-item label="二级机构：" prop="t2Code" style="display: inline-block;">
            <el-select v-model="queryForm.t2Code" placeholder="请选择三级机构" style="width: 220px;" @change="getSubComList()">
              <el-option v-for="item in comList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="三级机构：" prop="t3Code" style="display: inline-block;">
            <el-select v-model="queryForm.t3Code" placeholder="请选择二级机构" style="width: 220px;">
              <el-option v-for="item in subComList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="search-btn" @click="handleSearch()">搜索</div>
      </div>
      <div class="right-search">
        <div class="right-search-title">查看当前保单分布情况</div>
        <div class="right-search-radio">
          <el-radio-group v-model="queryForm.chooseType" @change="getMapDataFn">
            <el-radio label="1">按工作量</el-radio>
            <el-radio label="2">按保单件数</el-radio>
            <el-radio label="3">按保费</el-radio>
          </el-radio-group>
        </div>
      </div>
    </el-card>
    <div class="up-operate" @click="showMapFn()">
      {{isShowMap ? '收起分单视图' : '展开分单视图'}}
      <i v-if="isShowMap" class="el-icon-d-arrow-left down-icon"></i>
      <i v-else class="el-icon-d-arrow-right up-icon"></i>
    </div>
    <el-card class="policy-manage">
      <div class="policy-tab-nav">
        <div :class="{'tab-nav-item': true,'actived-item': currentTab == '1'}" @click="changeTab('1')">已分配保单</div>
        <!-- <div :class="{'tab-nav-item': true,'actived-item': currentTab == '2'}" @click="changeTab('2')">分配待确认保单</div> -->
        <div :class="{'tab-nav-item': true,'actived-item': currentTab == '3'}" @click="changeTab('3')">未分配保单</div>
        <!-- <div :class="{'tab-nav-item': true,'actived-item': currentTab == '4'}" @click="changeTab('4')">异常保单</div> -->
      </div>
      <div class="policy-tab-body">
        <PolicyDataShow :currentTab="currentTab"></PolicyDataShow>
      </div>
    </el-card>
  </div>
</template>

<script>
import PolicyDataShow from '../components/policyDataShow.vue'
import { getCompanyList, getMapData } from '../../../api/renewalPlatformApi/index';
import LabelsData from "../china-pp";

export default {
  name: 'PolicyManage',
  components: {
    PolicyDataShow,
  },
  data() {
    return {
      map: null,
      isShowIcon: true,
      queryForm: {
        t2Code: 8601,
        t3Code: 860101,
        chooseType: '1'
      },
      comList: [],
      subComList: [],
      currentTab: '1',
      isShowMap: true,
      mapData: {
        mapTipList: [],
        mapLineList: [],
      },
      stateOpt: { 1: '已分配', 2: '已分配' },
      keyCodeA: { 1: 'assignedFee', 2: 'assignedInsurance', 3: 'assignedWorkload' },
      keyCodeB: { 1: 'notAssignedFee', 2: 'notAssignedInsurance', 3: 'notAssignedWorkload' },
      listInfo:[],
      infoDate:""
    }
  },
  mounted() {
    this.infoDate = this.$route.query.placeCode
    // this.initMap();
    this.getComList();
    this.getSubComList();
    this.getMapDataFn();
    // this.initSubMap();
  },
  methods: {
    getMapDataFn() {
      getMapData(this.queryForm).then(res => { 
        if (res.code == 200) {
          this.listInfo = res.data
          let arr = [];
          let brr = [];
          res.data.forEach(item => {
            let numP = null;
            let numQ = null;
            if (item.assignedStatus == 1) {
              numP = item[this.keyCodeA[this.queryForm.chooseType]];
            } else if (item.assignedStatus == 2) {
              numP = item[this.keyCodeB[this.queryForm.chooseType]];
            } else if (item.assignedStatus == 3) {
              numP = item[this.keyCodeA[this.queryForm.chooseType]];
              numQ = item[this.keyCodeB[this.queryForm.chooseType]];
            }
            let temp = {
              name: item.areaName,
              numP,
              numQ,
              pos: JSON.parse(item.centerTitude),
              state: item.assignedStatus
            }
            arr.push(temp);
            brr.push({ adcode: item.placeCode, pathList: JSON.parse(item.pathList) });

          })
          this.mapData.mapTipList = arr;
          this.mapData.mapLineList = brr;
          this.initSubMap();
          this.showNeedRange(res.data,arr)
        }
      });
    },
    // 
   showNeedRange(list,arrList) {
      const _this = this;
      list.forEach(item => {
        if (item.assignedStatus == 1) {
          item.numP = item[this.keyCodeA[this.queryForm.chooseType]];
        } else if (item.assignedStatus == 2) {
          item.numP = item[this.keyCodeB[this.queryForm.chooseType]];
        } else if (item.assignedStatus == 3) {
          item.numP = item[this.keyCodeA[this.queryForm.chooseType]];
          item.numQ = item[this.keyCodeB[this.queryForm.chooseType]];
        }else{
          item.numP = 0
          item.numQ = 0
        }
        if(item.numP>0 && item.numQ == 0){
          item.background = '#F8CCC1'
        }else if(item.numP==0 && item.numQ > 0){
          item.background = '#F1E9C4'
        }else if(item.numQ>0 && item.numP > 0){
          item.background = '#ABEFEA'
        }else if(item.numQ == 0 && item.numP == 0){
          item.background = '#F8CCC1'
        }
        if (item.placeCode == this.infoDate) {
          let path = JSON.parse(item.pathList);
          let polygon = new AMap.Polygon({
            map: _this.map,
            fillOpacity: 0.6,
            path,
            zindex: 9999,
            strokeColor: `${item.background}`,
            fillColor: `${item.background}`,
          });
          polygon.on('click', (e) => {
              this.showInfoP(e.lnglat.lat,e.lnglat.lng,e.target._opts.path)
            })
          let pos = [];
          path.forEach(item => {
            pos.push({ lat: item[1], lng: item[0] });
          })
          _this.addTextFn(item.areaName, this.calculateCenter(pos))
          _this.map.setFitView();
        }
      });
     },
    // 获取绘制区域的中心
    calculateCenter(lnglatarr) {
      console.log('lnglatarr: ', lnglatarr)
      let total = lnglatarr.length;
      let X = 0, Y = 0, Z = 0;
      lnglatarr.map((item) => {
        let lng = (item.lng * Math.PI) / 180;
        let lat = (item.lat * Math.PI) / 180;
        let x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;
      let Lng = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      return new AMap.LngLat((Lng * 180) / Math.PI, (Lat * 180) / Math.PI);
    },
    addTextFn(name, position) {
      this.currentPosition = position;
      let text = new AMap.Text({
        text: name,
        anchor:'center', // 设置文本标记锚点
        cursor:'pointer',
        angle:10,
        style:{
          'padding': '.75rem .25rem',
          'border-radius': '.25rem',
          'border-width': 0,
          'text-align': 'center',
          'font-size': '18px',
          'color': 'black',
          'background-color': '#fff0'
        },
        position
      });
      text.setMap(this.map);
    },
    getComList() {
      getCompanyList({ companyType: '2' }).then((res) => {
        if (res.code === 200) {
          res.data.forEach(item => {
            let temp = {
              label: item.companyName,
              value: item.companyCode,
              placeCode: item.placeCode,
            }
            this.comList.push(temp);
          });
        }
      }).finally(() => {})
    },
    getSubComList() {
      this.subComList = [];
      getCompanyList({ companyType: '3', parentCode: this.queryForm.t2Code }).then((res) => {
        if (res.code === 200) {
          res.data.forEach(item => {
            let temp = {
              label: item.companyName,
              value: item.companyCode,
              placeCode: item.placeCode,
            }
            this.subComList.push(temp);
          });
        }
      }).finally(() => {})
    },
    // 展示搜索条件
    showIconFn(fg) {
      this.isShowIcon = fg;
    },
    // 二三级机构搜索
    handleSearch() {
      this.getMapDataFn();
    },
    // 切换Tab
    changeTab(idx) {
      this.currentTab = idx;
    },
    // 是否展开视图
    showMapFn() {
      this.isShowMap = !this.isShowMap;
    },
    initMap() {
      let disCountry = new AMap.DistrictLayer.Country({
        zIndex: 10,
        SOC: 'CHN',
        depth:1,
        styles: {
          'nation-stroke':'#ff0000',
          'coastline-stroke':'#0088ff',
          'province-stroke':'grey',
        }
      })
      this.map = new AMap.Map("policyMap",{
        zooms: [4.2, 8],
        center:[106.122082, 33.719192],
        zoom: 4.6,
        isHotspot: false,
        defaultCursor:'pointer',
        layers:[
          disCountry
        ],
        viewMode:'3D',
      })
      this.map.addControl(new AMap.Scale());
      this.map.addControl(new AMap.ToolBar({ liteStyle: true }));
      const _this = this;
      this.map.on('complete',function(){
        let layer = new AMap.LabelsLayer({
          // 开启标注避让，默认为开启，v1.4.15 新增属性
          collision: false,
          // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
          animation: true,
        });
        console.log(LabelsData)
        for (let i = 0; i < LabelsData.length; i++) {
          let labelsMarker = new AMap.LabelMarker(LabelsData[i]);
          layer.add(labelsMarker);
        }
        _this.map.add(layer);
      })
      
      let newData = [
        {
          name: '广东分公司',
          num: '222',
          pos: ['113.280637', '23.125178'],
          state: '1',
        },
        {
          name: '河南分公司',
          num: '456',
          pos: ['113.665412', '34.757975'],
          state: '2',
        },
        {
          name: '山东分公司',
          num: '854',
          pos: ['117.000923', '36.675807'],
          state: '2',
        },
        {
          name: '上海分公司',
          num: '54655',
          pos: ['121.472644', '31.231706'],
          state: '3',
        },
      ]
      newData.forEach((item) => {
        let markerContent1 = `<div style="display: block; min-width: 100px; text-wrap: nowrap; padding: 4px 10px; font-size: 14px; color: #B82322;background-color: #feccc2c4;">
          <div style="text-align: center;padding: 4px 0;">${item.name}</div>
          <div style="text-align: center;padding: 4px 0;">${item.state}: ${item.num}</div>
        </div>`
        let markerContent2 = `<div style="display: block; min-width: 100px; text-wrap: nowrap; padding: 4px 10px; font-size: 14px; color: #168696; background-color: #c4f6fdc4;">
          <div style="text-align: center;padding: 4px 0;">${item.name}</div>
          <div style="text-align: center;padding: 4px 0;">${item.state}: ${item.num}</div>
        </div>`
        let markerContent3 = `<div style="display: block; min-width: 100px; text-wrap: nowrap; padding: 4px 10px; font-size: 14px; color: #927828; background-color: #fde1b4c4;">
          <div style="text-align: center;padding: 4px 0;">${item.name}</div>
          <div style="text-align: center;padding: 4px 0;">${item.state}: ${item.num}</div>
        </div>`
        let marker = new AMap.Marker({
          position: item.pos,
          content: item.state == '1' ? markerContent1 : item.state == '2' ? markerContent2 : markerContent3,
        })
        this.map.add(marker)
      })
    },
    initSubMap() {
      // this.map = new AMap.Map("policyMap",{
      //   center: [116.30946, 39.937629],
      //   zoom: 8
      // });
      // const _this = this;
      this.showDividerCircle();
      // this.mapData.mapTipList.forEach(item => {
      //   let background = ''
      //   if( item.numP>0 && item.numQ == 0) background = '#F9E2DF'
      //   if( item.numP==0 && item.numQ > 0) background = '#CFFBF2'
      //   if( item.numQ>0 && item.numP > 0)  background = '#FEF6E8'
      //   if( item.numQ == null && item.numP == null)  background = '#CFFBF2'

      //   let markerContent1 = `<div style="display: block; min-width: 100px; text-wrap: nowrap; padding: 4px 10px; font-size: 14px; color: #B82322;background-color: ${background};">
      //     <div style="text-align: center;padding: 4px 0;">${item.name}</div>
      //     <div style="text-align: center;padding: 4px 0;">${this.stateOpt[item.state]}: ${item.numP || 0}</div>
      //   </div>`


      //   let markerContent2 = `<div style="display: block; min-width: 100px; text-wrap: nowrap; padding: 4px 10px; font-size: 14px; color: #168696; background-color: ${background};">
      //     <div style="text-align: center;padding: 4px 0;">${item.name}</div>
      //     <div style="text-align: center;padding: 4px 0;">${this.stateOpt[item.state]}: ${item.numP || 0}</div>
      //   </div>`
      //   let markerContent3 = `<div style="display: block; min-width: 100px; text-wrap: nowrap; padding: 4px 10px; font-size: 14px; color: #927828; background-color: ${background}" >
      //     <div style="text-align: center;padding: 4px 0;">${item.name}</div>
      //     <div style="text-align: center;padding: 4px 0;">未分配: ${item.numP || 0}</div>
      //     <div style="text-align: center;padding: 4px 0;">已分配: ${item.numQ || 0}</div>
      //   </div>`
      //   let marker = new AMap.Marker({
      //     position: item.pos,
      //     content: item.state == '1' ? markerContent1 : item.state == '2' ? markerContent2 : markerContent3,
      //   })
      //   _this.map.add(marker)
      // });
    },
    // 回显圈
    showDividerCircle() {
      this.map = new AMap.Map("policyMap",{
        center: [116.30946, 39.937629],
        zoom: 8
      });
      const _this = this;
      this.mapData.mapLineList.forEach(item => {
        //行政区划查询
        let opts = {
          subdistrict: 1,   // 返回下一级行政区
          showbiz: false  // 最后一级返回街道信息
        };
        // 注意：需要使用插件同步下发功能才能这样直接使用
        let district = new AMap.DistrictSearch(opts);
        district.setLevel('city'); // 行政区级别
        district.setExtensions('all');
        // 行政区查询：按照adcode进行查询可以保证数据返回的唯一性
        district.search(item.adcode + '', function (status, result) {
          if (status === 'complete') {
            let path = result.districtList[0].boundaries;
            let len = path.length - 1;
            // let polygon = new AMap.Polygon({
            //   map: _this.map,
            //   strokeWeight: 1,
            //   strokeColor: '#0091ea',
            //   fillColor: '#80d8ff',
            //   fillOpacity: 0,
            //   path: path[len],
            // });
            _this.map.setFitView();
            // polygon.on('mouseover', (e) => {
            //   console.log(e,"eeeeeeeeeeeee");
            // })
          }
        });
      });
    },
    showInfoP(lnt,lng,path){
      let arrCoordinate = []
      this.listInfo.forEach( (i ,index) =>{
        if(i.placeCode == this.infoDate){
          i.temporarily = JSON.parse(i.pathList)
          this.listInfo[index].temporarily.forEach( k =>{
            path.forEach( j => {
              if(k[1] == j[1] && k[0] == j[0]){
                arrCoordinate.push(this.listInfo[index])
              }
            })
          })
          }
        })
      this.getNumber(lnt,lng,arrCoordinate[1])
    },
    // 提取数字
    getNumber(lnt,lng,e){
      let list = []
      list.push(e)
      list.forEach(item => {
        if (item.assignedStatus == 1) {
          item.numP = item[this.keyCodeA[this.queryForm.chooseType]];
        } else if (item.assignedStatus == 2) {
          item.numP = item[this.keyCodeB[this.queryForm.chooseType]];
        } else if (item.assignedStatus == 3) {
          item.numP = item[this.keyCodeA[this.queryForm.chooseType]];
          item.numQ = item[this.keyCodeB[this.queryForm.chooseType]];
        }else{
          item.numP = ''
          item.numQ = ''
        }
      })
      this.getInfo(lnt,lng,list)
  },
    getInfo(lnt,lng,list){
      var info = [];
      info.push(`<p class='input-item'>未分配: ${list[0].numP || 0}</p>`);
      info.push(`<p class='input-item'>已分配: ${list[0].numQ || 0}</p>`);
      let infoDate = new AMap.InfoWindow({
      anchor: "top-left",
      content: info.join("<br/>")  //使用默认信息窗体框样式，显示信息内容
      });
      var position = [lng,lnt];
      infoDate.open(this.map,position);
    }
  },
}
</script>

<style lang="scss" scoped>
.policy-manage-bg {
  #policyMap {
    width: 100%;
    height: 520px;
  }
  .map-bg{
    position: relative;
    .search-bg-a, .search-bg-b{
      position: absolute;
      top: 26px;
      left: 30px;
    }
    .search-bg-a{
      font-size: 22px;
      padding: 10px;
      background: #0090DA;
      color: white;
    }
    .search-bg-b{
      font-size: 14px;
      display: flex;
      align-items: center;
      background: white;
      color: black;
      box-shadow: 2px 2px 2px rgba(182, 182, 182, 0.627);
      .search-btn{
        line-height: 53px;
        text-align: center;
        background: #0090DA;
        color: white;
        padding: 0 20px;
        margin-left: 20px;
        cursor: pointer;
      }
    }
    .right-search{
      position: absolute;
      top: 20px;
      right: 26px;
      padding: 10px 20px;
      background-color: #fff;
      .right-search-title{
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      .right-search-radio{}
    }
  }
  .policy-manage {
    .policy-tab-nav {
      display: flex;
      align-items: center;
      .tab-nav-item {
        flex: 1;
        font-size: 18px;
        text-align: center;
        padding: 12px;
        background-color: #f5f5f5;
        color: #afafaf;
        cursor: pointer;
        margin-left: 10px;
      }
      .actived-item {
        cursor: default;
        background-color: #e6f6ff;
        color: #25a0e0;
      }
      .tab-nav-item:nth-child(1) {
        margin: 0;
      }
    }
    .policy-tab-body {
    }
  }
  .up-operate{
    width: 100%;
    text-align: center;
    padding: 16px 0;
    background: #0090DA;
    color: white;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    .up-icon{
      transform: rotate(90deg);
    }
    .down-icon{
      transform: rotate(90deg);
    }
  }
}
</style>
